/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.inmp.task;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;

import com.sinodata.bsm.common.vo.Event;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.inmp.cache.CacheFactory;
import com.sinodata.bsm.inmp.cache.ResCache;
import com.sinodata.bsm.inmp.message.Messenger;
import com.sinodata.bsm.inmp.util.DBConnectionUtil;
import com.sinodata.bsm.inmp.util.FilePersistUtil;
import com.sinodata.bsm.inmp.util.InmpEvent;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-6-20 下午3:17:00          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
@SuppressWarnings("deprecation")
public class StorEventJob implements StatefulJob {

    private static final Logger logger = Logger.getLogger("opevent");

    private static String EVENT_STOR_FILE = "store_event";

    private ResCache resCache = (ResCache) CacheFactory.getCache(ResCache.class);

    private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        String lastTime = "";
        String now = "";
        try {
            now = sdf1.parse(getCurrentTime()).getTime() + "";
        } catch (Exception e) {
            logger.error("[ERROR]\tFailed when get postgre current time ", e);
            return;
        }

        try {
            lastTime = (String) FilePersistUtil.getPersistentData(EVENT_STOR_FILE);
        } catch (Exception e) {
            lastTime = "";
        }

        if (lastTime == null || lastTime.length() < 1) {
            try {
                FilePersistUtil.savePersistentData(EVENT_STOR_FILE, now);
                //                FilePersistUtil.savePersistentData(EVENT_STOR_FILE, "1370130508000");
            } catch (Exception e2) {
                logger.error(e2);
            }
            return;
        }

        //获取事件
        String sql = buildSql(lastTime, now);
        List<InmpEvent> list = getLastEvents(sql);
        //发送事件
        send(list);
        try {
            FilePersistUtil.savePersistentData(EVENT_STOR_FILE, now);
        } catch (Exception e2) {
            logger.error(e2);
        }

    }

    /**
     * 
     * @param sTime
     * @param eTime
     * @return
     */
    private String buildSql(String sTime, String eTime) {
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT");
        sb.append(" A .createtime,");
        sb.append(" A .modtime,");
        sb.append(" A .previousseverity,");
        sb.append(" A .severity,");
        sb.append(" A .mmessage,");
        sb.append(" A.SOURCE,");
        sb.append(" A.entity,");
        sb.append(" A.category,");
        sb.append(" A . ID");
        sb.append(" FROM");
        sb.append(" alert A");
        sb.append(" where ");
        sb.append(" a.createtime >='" + sTime + "'");
        sb.append(" and a.createtime<'" + eTime + "'");
        sb.append(" OR(");
        sb.append(" a.modtime >='" + sTime + "'");
        sb.append("  and a.modtime <'" + eTime + "'");
        sb.append(" )");
        sb.append(" order by a.createtime asc,");
        sb.append(" a.modtime asc");
        return sb.toString();
    }

    private void send(List<InmpEvent> eList) {
        if (eList == null) {
            return;
        }

        System.out.println(eList.size());
        for (InmpEvent iEvent : eList) {
            try {
                System.out.println(iEvent.toString());

                Res res = resCache.getResByIpForStor(iEvent.getSource().split("[_]")[0]);
                if (res == null) {
                    continue;
                }
                Event event = new Event();
                event.setResId(res.getId());
                event.setOccurTime(iEvent.getCreateTime());
                event.setEventTypeId(312100000000001L);
                event.setLastOccurTime(iEvent.getModTime());
                event.setMsg(iEvent.getMessage());
                event.setObjectId(iEvent.getEntity());
                if ("5".equals(iEvent.getSeverity())) {//产生一个恢复事件
                    event.setLevel(1);
                    event.setStatus(2);
                    event.setCatalog(2);
                } else { //产生一个新事件
                    event.setLevel(Integer.parseInt(iEvent.getSeverity()) + 1);
                    event.setStatus(0);
                    event.setCatalog(1);
                }

                Messenger.getInstance().sendEvent(event);
            } catch (Exception e) {
                logger.error(e);
            }

        }
    }

    /**
     * 获取最近的事件数据
     * @param sql
     * @return
     */
    private List<InmpEvent> getLastEvents(String sql) {
        logger.info(sql);

        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        List<InmpEvent> values = new ArrayList<InmpEvent>();
        try {
            conn = DBConnectionUtil.getInstance().getStorConnection();
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            if (rs == null) {
                return null;
            }
            while (rs.next()) {
                try {
                    InmpEvent event = new InmpEvent();
                    event.setCreateTime(sdf1.parse(sdf1.format(Long.parseLong(rs.getString(1)))));
                    event.setModTime(sdf1.parse(sdf1.format(Long.parseLong(rs.getString(2)))));
                    event.setPreSeverity(rs.getString(3));
                    event.setSeverity(rs.getString(4));
                    event.setMessage(rs.getString(5));
                    event.setSource(rs.getString(6));
                    event.setEntity(rs.getString(7));
                    event.setCategory(rs.getString(8));
                    event.setId(rs.getString(9));
                    event.toString();
                    values.add(event);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            logger.error(e);
            return null;
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) {

                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {

                }
            }
            DBConnectionUtil.getInstance().returnConn(conn);
        }
        return values;
    }

    /**
     * 获取当前时间
     * @return
     * @throws Exception
     */
    public String getCurrentTime() throws Exception {
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        String result = "";
        try {
            conn = DBConnectionUtil.getInstance().getStorConnection();
            statement = conn.createStatement();
            rs = statement.executeQuery("select now()");
            if (rs == null) {
                return null;
            }
            while (rs.next()) {
                result = rs.getString(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) {
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                }
            }
            DBConnectionUtil.getInstance().returnConn(conn);
        }
        return result;
    }

    public static void main(String[] args) {
        String i = "172.168.1";
        String[] a = i.split("[_]");
        if (a != null) {
            System.out.println(a.length);
            for (int ii = 0; ii < a.length; ii++) {
                System.out.println(a[ii]);
            }
        }

        try {
            FilePersistUtil.savePersistentData(EVENT_STOR_FILE, "1371708297301");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
